//
//  MSDBManager.m
//  MagicSword
//
//  Created by Netease on 15/11/19.
//  Copyright © 2015年 Jonear. All rights reserved.
//

#import "MSDBManager.h"
#import "MSHeroInfo.h"
#import "MSWeaponInfo.h"

#define DB_HEROINFOARRAYKEY     @"DB_HEROINFOARRAYKEY"
#define DB_STOREARRAYKEY        @"DB_STOREARRAYKEY"
#define DB_PASSSESSIONKEY       @"DB_PASSSESSIONKEY"
#define DB_PASSCHAPTERYKEY      @"DB_PASSCHAPTERYKEY"
#define DB_MaxHeroCount         @"DB_MaxHeroCount"

@implementation MSDBManager {
    NSUserDefaults *_dbDictionary;
}

+ (id)shareManager {
    static MSDBManager *dbMgr = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dbMgr = [[MSDBManager alloc] init];
    });
    return dbMgr;
}

- (id)init {
    self = [super init];
    if (self) {
        _dbDictionary = [NSUserDefaults standardUserDefaults];
    }
    return self;
}

- (void)saveDBHeroArray:(NSArray *)heroArray {
    NSMutableArray *array = [NSMutableArray array];
    for (MSHeroInfo *heroInfo in heroArray) {
        [array addObject:[MSHeroInfo getDictFromHeroInfo:heroInfo]];
    }
    [_dbDictionary setObject:array forKey:DB_HEROINFOARRAYKEY];
}

- (NSArray *)loadDBHeroArray {
    NSMutableArray *array = [NSMutableArray array];
    NSArray *heroArray = [_dbDictionary objectForKey:DB_HEROINFOARRAYKEY];
    for (NSDictionary *heroInfo in heroArray) {
        [array addObject:[MSHeroInfo getHeroInfoFromDict:heroInfo]];
    }
    return array;
}

- (void)saveDBStoreWeapon:(NSArray *)storeArray {
    NSMutableArray *array = [NSMutableArray array];
    for (MSWeaponInfo *info in storeArray) {
        [array addObject:[MSWeaponInfo getDictFromInfo:info]];
    }
    [_dbDictionary setObject:array forKey:DB_STOREARRAYKEY];
}

- (NSArray *)getDBStoreWeaponArray {
    NSMutableArray *array = [NSMutableArray array];
    NSArray *heroArray = [_dbDictionary objectForKey:DB_STOREARRAYKEY];
    for (NSDictionary *heroInfo in heroArray) {
        [array addObject:[MSWeaponInfo getInfoFromDict:heroInfo]];
    }
    return array;
}

- (void)savePassSession:(NSInteger)session Chapter:(NSInteger)chapter {
    [_dbDictionary setObject:@(session) forKey:DB_PASSSESSIONKEY];
    [_dbDictionary setObject:@(chapter) forKey:DB_PASSCHAPTERYKEY];
}
- (NSInteger)getPassSession {
    return [[_dbDictionary objectForKey:DB_PASSSESSIONKEY] integerValue];
}
- (NSInteger)getPassChapter {
    return [[_dbDictionary objectForKey:DB_PASSCHAPTERYKEY] integerValue];
}

- (void)saveMaxHeroCount:(NSInteger)count {
    [_dbDictionary setObject:@(count) forKey:DB_MaxHeroCount];
}
- (NSInteger)getMaxHeroCount {
    NSInteger count = [[_dbDictionary objectForKey:DB_MaxHeroCount] integerValue];
    if (count < 3) {
        count = 3;
    }
    return count;
}

- (void)sync {
    [_dbDictionary synchronize];
}

@end
